from flask_login import LoginManager
from flask_login import login_user, logout_user, login_required
from flask import session

from script.model.TagUser import *
from script.model.TagCategory import *
from script.utils.request_utils import *
from script.api.general_code import *
from config import ALLOW_REGISTER
from main import app, db
import os

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_message = "请先登录"


@login_manager.user_loader
def user_load(user_id):
    user = TagUser.query.filter_by(id=user_id).first()
    return user


@app.route('/api/login/', methods=['GET', 'POST'])
def login():
    state, user_name, password = get_form_need("username", "password")
    if state:
        user = TagUser.query.filter_by(user_name=user_name).first()
        if user:
            if user.check_password_hash(password):
                login_user(user)
                session.permanent = True
                return get_success_code_with_data("user", user.to_map())
            else:
                return LOGIN_PASSWORD_ERROR
        else:
            return LOGIN_USER_NOT_FOUND


@app.route('/api/register/', methods=['GET', 'POST'])
def register():
    if not ALLOW_REGISTER:
        return REGISTER_NOT_ALLOW
    state, username, password = get_form_need("username", "password")
    if state:
        user = TagUser.query.filter_by(user_name=username).first()
        if user:
            return REGISTER_USER_EXIST
        else:
            new_user = TagUser(user_name=username)
            new_user.generate_password_hash(password)
            new_user.user_default_category = TagCategory(user_id=new_user.id, category_name="默认")

            db.session.add(new_user)
            db.session.commit()

            return REGISTER_SUCCESS


@app.route('/api/logout/', methods=['GET', 'POST'])
@login_required
def logout():
    logout_user()
    return LOGOUT_SUCCESS


@app.route('/api/get_info/', methods=['GET', 'POST'])
@login_required
def get_username():
    info_map = current_user.to_map()
    info_map["code"] = 1
    return info_map


@app.route('/api/check/', methods=['GET', 'POST'])
@login_required
def check_cookie():
    return get_code(1, "ok")

